import {
  _decorator,
  CCInteger,
  Component,
  Enum,
  EventMouse,
  Node,
  Sprite,
} from "cc";
import { SunManager } from "./manager/SunManager";
import { MouseManager } from "./manager/MouseManager";
import { CardState, PlantType } from "./Global";
const { ccclass, property } = _decorator;

@ccclass("Card")
export class Card extends Component {
  private cardState: CardState = CardState.Cooling; // 卡牌状态

  @property({ type: Enum(PlantType) })
  public plantType: PlantType;

  @property(Node)
  public cardLight: Node = null; // 卡牌亮着的效果
  @property(Node)
  public cardGray: Node = null; // 卡牌灰着的效果
  @property(Sprite)
  public cardMask: Sprite = null; // 卡牌遮罩
  @property(CCInteger)
  public cdTime: number = 30; // 卡牌冷却时间
  private cdTimer: number = 0; // 卡牌冷却计时器
  @property({ type: CCInteger, tooltip: "卡牌需要阳光的点数" })
  private needSunPoint: number = 50;

  start() {
    this.cdTimer = this.cdTime;
  }

  update(deltaTime: number) {
    switch (this.cardState) {
      case CardState.Cooling:
        this.CoolingUpdate(deltaTime);
        break;
      case CardState.WaitingSun:
        this.WaitingSunUpdate();
        break;
      case CardState.Ready:
        this.ReadyUpdate();
        break;
    }
  }
  /**
   * 冷却刷新
   * @param deltaTime
   */
  private CoolingUpdate(deltaTime: number) {
    this.cdTimer -= deltaTime;
    this.cardMask.fillRange = -(this.cdTimer / this.cdTime);
    if (this.cdTimer <= 0) {
      this.transitionToWaitingSun();
    }
  }
  /**
   * 卡牌状态从冷却中过渡到等待阳光充足
   */
  transitionToWaitingSun() {
    this.cardState = CardState.WaitingSun;
    this.cardLight.active = false;
    this.cardGray.active = true;
    this.cardMask.node.active = false;
  }

  /**
   * 等待阳光充足刷新
   */
  private WaitingSunUpdate() {
    if (this.needSunPoint <= SunManager.Instance.SunPoint) {
      this.transitionToReady();
    }
  }

  /**
   * 准备种植刷新
   */
  private ReadyUpdate() {
    if (this.needSunPoint > SunManager.Instance.SunPoint) {
      this.transitionToWaitingSun();
    }
  }
  /**
   * 将卡牌状态转换为准备状态。
   */

  transitionToReady() {
    this.cardState = CardState.Ready;
    this.cardLight.active = true;
    this.cardGray.active = false;
    this.cardMask.node.active = false;
  }

  /**
   * 将卡牌状态转换为冷却中状态。
   */
  transitionToCooling() {
    this.cardState = CardState.Cooling;
    this.cdTimer = this.cdTime;
    this.cardLight.active = false;
    this.cardGray.active = true;
    this.cardMask.node.active = true;
  }

  onClick(event: EventMouse) {
    // 阳光值的限制
    if (this.needSunPoint > SunManager.Instance.SunPoint) return;
    const isSuccess = MouseManager.Instance.addPlant(this.plantType, event);
    if (isSuccess) {
      SunManager.Instance.subSun(this.needSunPoint);
      this.transitionToCooling();
    }
  }
}
